﻿using System;
using System.Collections;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;


namespace KineBall
{
    public class CircularProgressBar
    {
        public Vector2 center;
        public float radius;
        public float thickness;

        public int currentProgress = 0;

        private Texture2D pixel;
        private ArrayList vectors;

        public CircularProgressBar(GraphicsDevice graphicsDevice, Vector2 center, float radius, float thickness, Color color)
        {
            this.center     = center;
            this.radius     = radius;
            this.thickness  = thickness;

            pixel = new Texture2D(graphicsDevice, 1, 1);
            Color[] colorData = { color };
            pixel.SetData<Color>(colorData);

            vectors = new ArrayList();

            float maxAngle = 2 * (float)Math.PI;
            float step = maxAngle / 100.0f;

            for (float theta = 0; theta < maxAngle; theta += step)
            {
                vectors.Add(new Vector2(radius * (float)Math.Cos((double)theta), radius * (float)Math.Sin((double)theta)));
            }

            vectors.Add(new Vector2(radius * (float)Math.Cos(0), radius * (float)Math.Sin(0)));
        }

        public void SetProgress(int progress)
        {
            if (progress < 0)
            {
                currentProgress = 0;
            }
            else if (progress > 100)
            {
                currentProgress = 100;
            }
            else
            {
                currentProgress = progress;
            }
        }

        public void Increment(int increment)
        {
            if (currentProgress + increment > 100)
                currentProgress = 100;
            else
                currentProgress += increment;
        }

        public void SetPosition(Vector2 center)
        {
            this.center = center;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            if (vectors.Count < 2)
                return;

            for (int i = 1; i < currentProgress; i++)
            {
                Vector2 vector1 = (Vector2)vectors[i - 1];
                Vector2 vector2 = (Vector2)vectors[i];

                float distance = Vector2.Distance(vector1, vector2);

                float angle = (float)Math.Atan2((double)(vector2.Y - vector1.Y), (double)(vector2.X - vector1.X));

                spriteBatch.Draw(pixel, center + vector1, null, Color.White, angle, Vector2.Zero, new Vector2(distance, 1) * thickness, SpriteEffects.None, 0);
            }
        }
    }
}
